const fs = require('fs');
const path = require('path');
const config = require('../config');

function ensureDirSync(targetDirPath) {
    if (!fs.existsSync(targetDirPath)) {
        fs.mkdirSync(targetDirPath, { recursive: true });
    }
}

function resolveSafePath(relativeOrSubPath) {
    const baseDir = path.resolve(process.cwd(), config.BASE_DIR || './downloads');
    const resolvedPath = path.resolve(baseDir, relativeOrSubPath || '');
    if (!resolvedPath.startsWith(baseDir)) {
        throw new Error('Path traversal detected');
    }
    return resolvedPath;
}

module.exports = {
    ensureDirSync,
    resolveSafePath,
};
function safeJoin(...segments) {
    const joined = path.join(...segments);
    return path.normalize(joined);
}

module.exports.safeJoin = safeJoin;


